using DapperExtensionsNew.Data.Attributes;
using DapperExtensionsNew.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DapperExtensionsNew.Queryable.Analyzers
{
	public abstract class AbstractAnalyzer : IAnalyzer
	{
		protected abstract void Analyze(Context context);

		void IAnalyzer.Analyze(Context context)
		{
			Analyze(context);
		}

		protected Expression ConcatExpression(Expression left, Expression right)
		{
			IEnumerable<MethodInfo> value = MethodInfoUtil.StringConcatMethodInfos.Value;
			return Expression.Call(null, value.First((MethodInfo m) => m.GetParameters().Length == 2), left, right);
		}

		protected Expression ConcatExpression(Expression arg0, Expression arg1, Expression arg2)
		{
			IEnumerable<MethodInfo> value = MethodInfoUtil.StringConcatMethodInfos.Value;
			return Expression.Call(null, value.First((MethodInfo m) => m.GetParameters().Length == 3), arg0, arg1, arg2);
		}

		protected Expression CallAddParameters(Expression parametersExpr, Expression keyExpr, Expression valueExpr)
		{
			MethodInfo dynanicParametersAddMethod = MethodInfoUtil.DynanicParametersAddMethod;
			return Expression.Call(parametersExpr, dynanicParametersAddMethod, keyExpr, Expression.Convert(valueExpr, typeof(object)));
		}

		protected Expression CallStringBuilderAppend(Expression stringBuilderInst, Expression stringParam)
		{
			return Expression.Call(stringBuilderInst, MethodInfoUtil.StringBuilderAppend, stringParam);
		}

		protected string GetColumnName(Type modelType, string propertyName)
		{
			string result = propertyName;
			PropertyInfo property = modelType.GetProperty(propertyName);
			if (property != null)
			{
				ColumnAttribute columnAttribute = property.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
				if (columnAttribute != null && columnAttribute.Name != null)
				{
					result = columnAttribute.Name;
				}
			}
			return result;
		}
	}
}
